package com.zwb.demo.easyweb.core.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.zwb.demo.easyweb.core.exception.ExceptionCast;
import com.zwb.demo.easyweb.modules.database.entity.DatabaseCode;
import com.zwb.demo.easyweb.modules.database.entity.DatabaseType;
import com.zwb.demo.easyweb.modules.database.vo.DatabaseLinkVO;

import javax.sql.DataSource;

public class DbUtils {
    private static  DruidDataSource dataSource = new DruidDataSource();

    public static DataSource getDataSource(DatabaseLinkVO vo) {
        DatabaseType databaseType = DatabaseType.typeOf(vo.getDatabaseType());
        if (databaseType == null) {
            ExceptionCast.cast(DatabaseCode.NO_EXIT_DATABASE_TYPE);
        }
        if (databaseType.url(vo).equals(dataSource.getUrl())) {
            return dataSource;
        }
        dataSource.close();
        dataSource = new DruidDataSource();
        dataSource.setPassword(vo.getPassword());
        dataSource.setUsername(vo.getUsername());
        dataSource.setUrl(databaseType.url(vo));
        dataSource.setDriverClassName(databaseType.driverName());
        return dataSource;
    }
}
